package cn.wolfcode.trip.app.controller.websocket;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Controller
@ServerEndpoint(value="/ws/chatServer/{userId}/{targetId}/{type}")
public class WebSocket {
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    //特殊的注入应对方式 改变成静态然后在注入
    private ChatResponse response =new ChatResponse();
    /*@Autowired
    public void setResponse(ChatResponse response){
        WebSocket.response = response;
    }*/

    @OnOpen
    public void onOpen(@PathParam("userId") Long userId, @PathParam("targetId") Long targetId, @PathParam("type") Integer type, Session session){
        System.out.println(userId + "" +targetId + type);
        this.session = session;
        ServerManager.add(this);
//        response = getBean();
        response.start(userId,targetId,type,this);
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    @OnClose
    public void onClose(){
        response.close();
        ServerManager.remove(this);
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
}
